<template>
	<view>
		<uv-sticky offset-top="0" custom-nav-height="0">
			<view class="index_head">
				<view class="header-top">
					<view class="status_bar">
					</view>
					<view class="box" :style="{ 'height': menuButtonH + 'px' }">
						<!-- <view class="position">
							<text>东莞</text>
						</view> -->
						<view class="nav">
							<text class="nav-text">
								{{ config.name }}
							</text>
						</view>
					</view>
				</view>
			</view>
		</uv-sticky>
		<view class="home">
			<view class="banner">
				<uni-swiper-dot class="uni-swiper-dot-box" mode="round" field="content">
					<swiper class="swiper-box">
						<swiper-item v-for="item in banner" :key="item.id">
							<view class="swiper-item">
								<image class="banner-img" :src="item.picUrl" mode="aspectFill">
								</image>
							</view>
						</swiper-item>

					</swiper>
				</uni-swiper-dot>
			</view>
			<view class="search-box">
				<view class="project">
					<!-- <text class="project-t"></text> -->
					<text class="project-t">{{ opcData && Object.keys(opcData).length > 0 ? opcData.opcname : '项目选择'
						}}</text>
					<view class="project-left content0" @click="showPopupType">
						<text>查看项目</text>
						<view class="iconfont icon-erjiyemianjiantou01">

						</view>
					</view>
				</view>
				<!-- <view class="search-type">
					<view class="btn" v-for="(item, index) in typeList" :key="item.type" :class="{ 'on': opcData.type === item.type, ['content' + (index + 1)]: true }"
						@click="opcClickType(item.type)">
						{{ item.name }}
					</view>
				</view> -->
				<!-- <view class="search-input">
					<navigator class="left" url="/pages/index/search">
						<uv-input prefixIcon="search" prefixIconStyle="font-size: 22px;color: #909399"
							placeholder="搜索课程" border="none" clearable :customStyle="{
								'background': '#F7F6F9', 'height': ' 76rpx', 'borderRadius': '10rpx', 'padding': '0 25rpx'
							}"></uv-input>
					</navigator>
				</view> -->
			</view>
			<view class="courses-box">
				<!-- <view class="courses-box-title">
					推荐课程
				</view> -->
				<view class="courses-list">
					<view v-if="courseList.length > 0" v-for="item in courseList" :key="item.id" class="courses-item">
						<text class="type" :style="{ 'background': item.type == 0 ? '#FD3523' : '#F47900' }">{{
							item.type == 0 ? '初训' : '复训' }}</text>
						<view class="courses-item-top">
							<view class="courses-item-img">
								<image :src="item.pic" mode="aspectFill"></image>
							</view>
							<view class="courses-item-right">
								<view class="item-right-title">
									<text class="h1">{{ item.title }}</text>
									<view class="tag-list">
										<text v-for="tag in item.courseTags" :key="tag.id">{{ tag.tag }}</text>
									</view>
								</view>
								<view class="price">
									<view class="rmb">
										<text class="rmbicon">¥</text><text>{{ item.price }}</text>
									</view>
									<text class="original">原价¥ {{ item.oldPrice }}</text>
								</view>
							</view>
						</view>
						<view class="info">
							<text>发证机关：{{ item.certificate }} 课时时间：{{ item.hour }}课时
								考试方式：理论考试+实操考试</text>
						</view>
						<view class="bottom">
							<view class="bottom-left">
								<view class="pictures">
									<uv-avatar-group :urls="item.orderUsers.slice(0, 5).map(item => item.avatar)"
										size="20" gap="0.4"></uv-avatar-group>
									<!-- <view class="img-item" v-for="(item, index) in item.orderUsers.slice(0, 5)"
										:key="item.id">
										<image :src="item.avatar" mode=""></image>
									</view> -->
								</view>
								<text>{{ item.orderUsers.length }}人已领证</text>
							</view>
							<view class="apply" :class="{'disabled': item.buy}" @click="apply(item.id)">{{ item.buy ? '已报名' : '立即报名' }}</view>
						</view>
					</view>
					<div v-else>
						<uv-empty mode="data" icon="/static/notData.png"></uv-empty>
					</div>
				</view>
			</view>
		</view>

		<lff-barrage ref="lffBarrage"></lff-barrage>

		<guideStep v-if="stepShow" :step="step"></guideStep>
		<!-- <course-type-selector ref="typeSelector" @select="onTypeSelect" @tapselect="onTapSelect" /> -->
	</view>
</template>

<script>
import {
	getCourseList
} from '@/http/exam.js'
import {
	getBannerList,
	getConfigList,
	getMessageList
} from '@/http/user.js'
import guideStep from "@/components/xky-guideStep/xky-guideStep.vue";
import lffBarrage from '@/components/lff-barrage/lff-barrage.vue'

// import CourseTypeSelector from '@/components/course-type-selector/courseTypeSelector.vue'
import WebSocketClient from '@/utils/webSocket.js'

export default {
	components: {
		// CourseTypeSelector,
		guideStep,
		lffBarrage
	},

	data() {
		return {
			stepShow: false,
			step: {
				name: 'courses-guide',
				repeat: false,
				guideList: [
					{
						el: '.content0',
						tips: '工种类别切换',
						style: "border-radius: 8rpx;margin: 0",
						next: "完成"
					},
					// {
					// 	el: '.content1',
					// 	tips: '新考/初训点这里',
					// 	style: "border-radius: 8rpx;margin: 0",
					// 	next: "下一步"
					// },
					// {
					// 	el: '.content2',
					// 	tips: '复审/换证/复训点这里',
					// 	style: "border-radius: 8rpx;margin: 0",
					// 	next: "完成"
					// }
				]
			},
			checkboxValue: '',
			avatarUrl: '',
			menuButtonH: '',
			idx: 0,
			wxCode: '',
			courseList: [],
			opcData: {},
			options: {
				navTitleKey: 'name',
				childListKey: 'children',
				listKey: 'children',
				imageKey: 'pic',
				titleKey: 'name'
			},
			data: [],
			opcType: '',
			typeList: [
				{
					type: 0,
					name: '初训'
				},
				{
					type: 1,
					name: '复训'
				}
			],
			searchKey: '',
			banner: [],
			config: {},
			wsClient: null
		}
	},

	onShow() {
		// #ifndef H5
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		// console.log(this.menuButtonInfo);
		this.menuButtonH = menuButtonInfo.height + (menuButtonInfo.top / 2)
		// #endif
		// this.opcData = uni.getStorageSync('opcData')
		// if (!Object.keys(this.opcData).length > 0) {
		// 	this.$nextTick(() => {
		// 		this.showPopupType()
		// 	})
		// }
		this.opcData.opc = ''
		// 获取当前页面栈
		const pages = getCurrentPages()
		const currPage = pages[pages.length - 1]
		// 如果有搜索参数，更新搜索关键词并加载数据
		if (currPage.$vm.key) {
			this.searchKey = currPage.$vm.key
			this.opcData.opc = ''
			this.opcData.type = ''
			// 清除搜索参数，避免重复使用
			currPage.$vm.key = ''
			// 重新加载数据
			this.onLoadData()
		} else {
			this.onLoadData()
		}
		this.initWebSocket()
		
	},
	onUnload() {
		// this.wsClient.close()
	},
	onLoad(options) {
		this.getBannerList()
		// this.config = uni.getStorageSync('config')[0] || {}
		// let banner = uni.getStorageSync('banner') || []
		// this.banner = banner.filter(item => item.tabItem == 'course')
		// this.loadMessageList()
		
		// this.showPopupType()
	},
	onHide() {
		console.log('onHide');

		if (this.wsClient) {
			this.wsClient.close()
			this.wsClient = null
		}
	},
	methods: {
		loadMessageList(){
			getMessageList({pageNum:1,pageSize:50,type:'course'}).then(res => {
				console.log(res);
			})
		},
		getBannerList() {
			getBannerList().then(res => {
				this.banner = res.data.filter(item => item.tabItem == 'course')
				console.log(this.banner);
			})
			getConfigList().then(res => {
				this.config = res.data[0] || {}
			})
		},
		apply(id) {
			uni.navigateTo({
				url: `/pages/courses/detail?id=${id}`
			})
		},
		async onLoadData() {
			uni.showLoading({
				title: '加载中...',
				mask: true
			})
			let params = {
				...(this.searchKey ? { key: this.searchKey } : {}),
				opc: this.opcData.opc,
				type: this.opcData.type,
				pageNum: 1,
				pageSize: 10,
			}
			console.log(params);

			try {
				const res = await getCourseList(params)
				this.courseList = res.data.list
			} catch (err) {

				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		login() {
			this.$refs.applogin.show()
			// uni.navigateTo({
			// 	url:'/pages/login/login'
			// })
		},
		tapselect(val) {
			this.idx = val
		},
		showPopupType() {
			this.$refs.typeSelector.open()
		},
		opcClickType(type) {
			this.opcData.type = type
			uni.setStorageSync('opcData', this.opcData)
			this.onLoadData()
		},
		onTypeSelect(val) {
			console.log(val);
			this.opcData = {
				opc: val.id,
				opcname: val.name
			}
			this.searchKey = ''
			// uni.setStorageSync('opcData', this.opcData)
			this.stepShow = true
			this.onLoadData()
		},
		onTapSelect(index) {
			// 如果需要处理左侧选择事件
		},
		initWebSocket() {
			this.wsClient = new WebSocketClient({
				url: 'wss://batapi.qiananquang.com:8222',
				heartbeatInterval: 30000,
				maxReconnectAttempts: 5,
				socketKey: 'courseSocket'
			})

			this.wsClient.onTokenInvalid(() => {

				console.error('Token失效，断开连接')

				uni.removeStorageSync('token')

				// setTimeout(() => {
				// 	uni.redirectTo({
				// 		url: '/pages/login/login'
				// 	})
				// }, 1500)
			})

			this.wsClient.onOpen(() => {
				console.log('WebSocket已连接')
			})

			this.wsClient.onMessage((res) => {
				try {
					const data = JSON.parse(res.data)
					if(data.code == 200){	
						if(data.data.type == 'courses'){
							// console.log(data, '监听消息');
							this.$nextTick(() => {
								let nickname = data.data.nickname
								let maskedName = this.maskName(nickname)
								this.$refs.lffBarrage.add({item:{nickname:maskedName,courseName:data.data.courseName}})
							})	
						}
					}
					// switch (data.type) {
					// 	case 'punch':
					// 		// 处理打卡消息
					// 		this.handlePunchMessage(data)
					// 		break
					// 	case 'course':
					// 		// 处理课程更新消息
					// 		this.handleCourseMessage(data)
					// 		break
					// 	case 'notification':
					// 		// 处理通知消息
					// 		this.handleNotificationMessage(data)
					// 		break
					// }
				} catch (error) {
					console.error('解析消息失败:', error)
				}
			})

			this.wsClient.onError((error) => {
				console.error('WebSocket 错误:', error)
			})

			this.wsClient.onClose(() => {
				console.log('WebSocket 已关闭')
			})

			this.wsClient.connect()
		},
		maskName(nickname) {
			if(!nickname) return ''
			if(nickname.length == 2) {
				return nickname[0] + '*'
			} else if(nickname.length == 3) {
				return nickname[0] + '*' + nickname[2]
			} else if(nickname.length > 3) {
				return nickname[0] + '**' + nickname[nickname.length-1]
			}
			return nickname
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background: linear-gradient(180deg, #fc3826FF, #f49d95FF);
	background-size: 100% 345rpx;
	background-repeat: no-repeat;
	background-color: #F7F6F9;
}

.status_bar {
	height: var(--status-bar-height);
	width: 100%;
	opacity: 0;
}

.index_head {
	.header-top {
		background: linear-gradient(180deg, #FC3826, #F96052);

		.box {
			color: #fff;
			position: relative;
			height: 110rpx;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			/* #ifndef WEB */
			padding-bottom: 20rpx;
			/* #endif */
		}

		.position {
			align-self: center;
			font-size: 34rpx;
			position: absolute;
			left: 34rpx;
			z-index: 3;
			/* #ifdef WEB */
			top: 50%;
			transform: translate(0, -50%);
			/* #endif */

			/* #ifndef WEB */
			// top: calc(50%-20rpx);
			transform: translate(0, -50%);
			/* #endif */


		}

		.nav {
			.nav-text {
				flex: 1;
				font-size: 34rpx;
				font-weight: 700;
			}

			.nav-box {
				padding: 0 10rpx;
				font-size: 26rpx;
				text-align: center;
				display: flex;
				justify-content: space-evenly;
				align-items: center;
				background: #FFFFFF;
				border-radius: 50rpx;
				color: #FD3523;
				font-weight: 700;
				height: 60rpx;



			}
		}
	}
}

.home {
	.banner {
		height: 235rpx;
		background: #CBCBCB;
		border-radius: 14rpx;
		margin: 40rpx 40rpx 0 40rpx;

		.swiper-box {
			height: 235rpx;
		}

		.swiper-item {
			height: 235rpx;
		}

		.banner-img {
			width: 100%;
			height: 100%;
			border-radius: 15rpx;
		}
	}

	.search-box {
		padding: 40rpx 40rpx;
		background: #fff;

		.project {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.project-t {
				font-weight: 700;
				font-size: 34rpx;
				color: #333333;
			}

			.project-left {
				display: flex;
				justify-content: center;
				align-items: center;
				color: #999999;
				font-weight: 500;
				font-size: 24rpx;

				.iconfont {
					font-size: 24rpx;
				}
			}
		}

		.search-type {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 20rpx 0;

			.btn {
				height: 75rpx;
				line-height: 75rpx;
				background: #F7F6F9;
				border-radius: 10rpx;
				font-weight: 400;
				font-size: 30rpx;
				color: #333333;
				flex: 1;
				text-align: center;
				margin: 0 10rpx;
			}

			.on {
				background: #FD3523;
				color: #fff;
			}
		}
	}

	.courses-box {
		padding: 40rpx;

		.courses-box-title {
			font-size: 34rpx;
			color: #333333;
			display: block;
			text-align: left;
			margin-bottom: 30rpx;
		}

		.courses-list {
			.courses-item {
				padding: 28rpx;
				background: #FFFFFF;
				box-shadow: 0rpx 10rpx 57rpx 0rpx rgba(0, 0, 0, 0.09);
				border-radius: 10rpx;
				margin-bottom: 40rpx;
				position: relative;

				.type {
					position: absolute;
					right: 0;
					top: 0;

					color: #fff;
					font-size: 26rpx;
					border-radius: 8rpx;
					padding: 4rpx 8rpx;
					text-align: center;
				}

				// display: flex;
				// flex-direction: column;
				.courses-item-top {
					display: flex;

					image {
						width: 175rpx;
						height: 175rpx;
						border-radius: 4rpx;
					}

					.courses-item-img {
						position: relative;
						border-radius: 8rpx;
						overflow: hidden;

					}

					.courses-item-right {
						margin-left: 15rpx;
						display: flex;
						justify-content: space-between;
						flex-direction: column;


						.h1 {
							font-weight: 700;
							font-size: 32rpx;
							color: #12141A;
							margin-bottom: 10rpx;
						}

						.tag-list {
							display: flex;
							align-items: center;

							text {
								padding: 10rpx;
								background: #FDF7F2;
								border-radius: 4rpx;
								font-weight: 400;
								font-size: 22rpx;
								color: #E96C32;
								margin-right: 10rpx;
							}
						}

						.price {
							display: flex;
							align-items: baseline;

							.rmb {
								font-weight: 500;
								font-size: 40rpx;
								color: #FD3523;
								display: flex;
								align-items: center;

								.rmbicon {
									font-weight: 500;
									font-size: 28rpx;
									color: #FD3523;
								}
							}

							.original {
								margin-left: 15rpx;
								font-weight: 400;
								font-size: 18rpx;
								color: #999999;
								line-height: 48rpx;
								text-decoration-line: line-through;
							}
						}
					}
				}

				.info {
					font-weight: 400;
					font-size: 22rpx;
					color: #6F7581;
					background: #F7F6F9;
					border-radius: 4rpx;
					padding: 15rpx 20rpx;
					margin: 25rpx 0;
				}

				.bottom {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.bottom-left {
						display: flex;
					}

					.pictures {
						display: flex;
						align-items: center;

						.img-item {
							height: 40rpx;
							width: 40rpx;
							margin-left: -15rpx;

							image {
								width: 100%;
								height: 100%;
								border-radius: 50%;
							}
						}

						text {
							font-weight: 500;
							font-size: 24rpx;
							color: #12141A;
						}
					}


					.apply {
						width: 160rpx;
						height: 60rpx;
						line-height: 60rpx;
						background: #FD3523;
						box-shadow: 0rpx 5rpx 7rpx 0rpx rgba(253, 53, 35, 0.09);
						border-radius: 10rpx;
						font-weight: 600;
						font-size: 28rpx;
						color: #FFFFFF;
						text-align: center;
					}
					.disabled{
						background:#ffd4d0;
						color:#FD3523;
					}

				}
			}
		}
	}
}
</style>